const express = require('express')
const bodyParser = require('body-parser')
const cors = require('cors')
const path = require('path')
const os = require('os')
const fs = require('fs')
const { marked } = require('marked') // 使用结构化导入
const router = require('./router/index') // 引入 router 文件夹的 index.js

const app = express()

// 中间件配置
app.use(cors())
app.use(bodyParser.json())

// 配置静态文件目录
app.use('/uploads', express.static(path.join(__dirname, 'uploads')))
app.use(router)
app.use(express.static(path.join(__dirname)))

// 读取 Markdown 文件并转换为 HTML
app.get('/docs', (req, res) => {
  const filePath = path.join(__dirname, 'docs.md')
  fs.readFile(filePath, 'utf8', (err, data) => {
    if (err) {
      console.error(`读取文档失败: ${err.message}`)
      return res.status(500).send('文档读取失败')
    }
    try {
      const htmlContent = marked.parse(data)
      res.send(`
        <html>
        <head>
            <title>用户信息接口文档</title>
            <link rel="stylesheet" href="./markdown.css">
        </head>
        <body>
            ${htmlContent}
        </body>
        </html>
      `)
    } catch (parseErr) {
      console.error(`Markdown 解析失败: ${parseErr.message}`)
      res.status(500).send('文档解析失败')
    }
  })
})

// 日志中间件，用于记录请求信息
app.use((req, res, next) => {
  console.log(`收到请求: ${req.method} ${req.url} 来自: ${req.ip}`)
  next()
})

// 获取本地 IP 地址的函数
function getLocalIPAddress() {
  const interfaces = os.networkInterfaces()
  for (const name in interfaces) {
    for (const iface of interfaces[name]) {
      if (iface.family === 'IPv4' && !iface.internal) {
        return iface.address
      }
    }
  }
  return 'localhost'
}

const PORT = process.env.PORT || 3000

app.listen(PORT, '0.0.0.0', () => {
  const localIP = getLocalIPAddress()
  console.log(`服务器已启动，在本地访问: http://${localIP}:${PORT}`)
  console.log(`在本机访问: http://localhost:${PORT}`)
})
